import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';

class NotificationController extends GetxController
    with GetSingleTickerProviderStateMixin {
  NotificationController();

  // Tab控制器
  late TabController tabController;

  // 私聊列表
  final RxList<ChatRoom> privateChats = <ChatRoom>[].obs;

  // 群聊列表
  final RxList<ChatRoom> groupChats = <ChatRoom>[].obs;

  // 关注列表
  final RxList<User> followingUsers = <User>[].obs;

  // 粉丝列表
  final RxList<User> followers = <User>[].obs;

  // 未读消息计数
  final RxMap<int, int> unreadCounts = <int, int>{}.obs;

  // 用户缓存
  final RxMap<int, User> userCache = <int, User>{}.obs;

  // 加载状态
  final RxBool isLoading = true.obs;

  // 仓库
  final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();
  final ChatMessageRepository _chatMessageRepository = ChatMessageRepository();
  final UserRepository _userRepository = UserRepository();
  final UserFollowRepository _userFollowRepository = UserFollowRepository();

  // 初始化数据
  Future<void> _initData() async {
    isLoading.value = true;

    try {
      // 获取当前用户
      final userService = Get.find<UserService>();
      if (!userService.isLoggedIn.value) {
        isLoading.value = false;
        return;
      }

      final currentUserId = userService.currentUser.value!.id!;

      // 加载聊天列表
      await loadChatRooms(currentUserId);

      // 加载关注列表
      await loadFollowingUsers(currentUserId);

      // 加载粉丝列表
      await loadFollowers(currentUserId);

      update(["notification"]);
    } catch (e) {
      print('初始化通知页数据失败: $e');
    } finally {
      isLoading.value = false;
    }
  }

  // 刷新数据
  Future<void> refreshData() async {
    print('开始刷新数据');
    final userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) return;

    final currentUserId = userService.currentUser.value!.id!;

    // 重新加载聊天室数据
    await loadChatRooms(currentUserId);

    // 强制UI更新
    privateChats.refresh();
    groupChats.refresh();
    unreadCounts.refresh();
    print('数据刷新完成，未读消息数：${unreadCounts}');
    update(["notification"]);
  }

  // 加载聊天室列表
  Future<void> loadChatRooms(int currentUserId) async {
    try {
      // 清空旧数据
      privateChats.clear();
      groupChats.clear();
      unreadCounts.clear();

      final chatRooms = await _chatRoomRepository.getChatRoomsByUserId(
        currentUserId,
      );

      // 分类私聊和群聊
      privateChats.value = chatRooms.where((room) => !room.isGroup).toList();
      groupChats.value = chatRooms.where((room) => room.isGroup).toList();

      // 加载未读消息数
      for (var chatRoom in chatRooms) {
        final unreadCount = await _chatRoomRepository.getUnreadMessagesCount(
          chatRoom.id!,
          currentUserId,
        );
        print('聊天室 ${chatRoom.id} 未读消息数: $unreadCount');
        unreadCounts[chatRoom.id!] = unreadCount;
      }

      // 加载用户信息
      final allUserIds = _getAllUserIds(chatRooms, currentUserId);
      await _loadUserInfo(allUserIds);
    } catch (e) {
      print('加载聊天列表失败: $e');
    }
  }

  // 从聊天室获取所有用户ID
  Set<int> _getAllUserIds(List<ChatRoom> chatRooms, int currentUserId) {
    final Set<int> userIds = {};

    for (var room in chatRooms) {
      if (!room.isGroup && room.memberIds.isNotEmpty) {
        // 私聊，找出对方的ID
        for (var userId in room.memberIds) {
          if (userId != currentUserId) {
            userIds.add(userId);
          }
        }
      } else {
        // 群聊，添加所有成员ID
        userIds.addAll(room.memberIds);
      }
    }

    return userIds;
  }

  // 加载用户信息
  Future<void> _loadUserInfo(Set<int> userIds) async {
    for (var userId in userIds) {
      try {
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          userCache[userId] = user;
        }
      } catch (e) {
        print('加载用户 $userId 信息失败: $e');
      }
    }
  }

  // 加载关注列表
  Future<void> loadFollowingUsers(int currentUserId) async {
    try {
      final followingList = await _userFollowRepository.getFollowingUsers(
        currentUserId,
      );
      followingUsers.value = followingList;

      // 更新用户缓存
      for (var user in followingList) {
        if (user.id != null) {
          userCache[user.id!] = user;
        }
      }
    } catch (e) {
      print('加载关注列表失败: $e');
    }
  }

  // 加载粉丝列表
  Future<void> loadFollowers(int currentUserId) async {
    try {
      final followerList = await _userFollowRepository.getFollowerUsers(
        currentUserId,
      );
      followers.value = followerList;

      // 更新用户缓存
      for (var user in followerList) {
        if (user.id != null) {
          userCache[user.id!] = user;
        }
      }
    } catch (e) {
      print('加载粉丝列表失败: $e');
    }
  }

  // 获取私聊对方用户
  User? getPrivateChatUser(ChatRoom chatRoom) {
    final userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) return null;

    final currentUserId = userService.currentUser.value!.id!;

    for (var userId in chatRoom.memberIds) {
      if (userId != currentUserId) {
        return userCache[userId];
      }
    }

    return null;
  }

  // 进入聊天页面
  void enterChatRoom(ChatRoom chatRoom) {
    Get.toNamed('/chat/room', arguments: {'chatRoom': chatRoom})!.then((_) {
      // 从聊天页面返回时，刷新数据
      print('从聊天页面返回');
      refreshData();
    });
  }

  // 检查是否已关注某用户
  Future<bool> isFollowing(int userId) async {
    try {
      final userService = Get.find<UserService>();
      if (!userService.isLoggedIn.value) return false;

      final currentUserId = userService.currentUser.value!.id!;
      return await _userFollowRepository.isFollowing(currentUserId, userId);
    } catch (e) {
      print('检查关注状态失败: $e');
      return false;
    }
  }

  // 取消关注用户
  Future<void> unfollowUser(int userId) async {
    try {
      final userService = Get.find<UserService>();
      if (!userService.isLoggedIn.value) return;

      final currentUserId = userService.currentUser.value!.id!;

      // 取消关注
      final success = await _userFollowRepository.unfollowUser(
        followerId: currentUserId,
        followingId: userId,
      );

      if (success) {
        // 从关注列表中移除
        followingUsers.removeWhere((user) => user.id == userId);
        // 刷新UI
        update(["notification"]);
      }
    } catch (e) {
      print('取消关注失败: $e');
    }
  }

  // 关注用户
  Future<void> followUser(int userId) async {
    try {
      final userService = Get.find<UserService>();
      if (!userService.isLoggedIn.value) return;

      final currentUserId = userService.currentUser.value!.id!;

      // 关注用户
      final result = await _userFollowRepository.followUser(
        followerId: currentUserId,
        followingId: userId,
      );

      if (result != null) {
        // 刷新关注列表
        await loadFollowingUsers(currentUserId);
        // 刷新UI
        update(["notification"]);
      }
    } catch (e) {
      print('关注用户失败: $e');
    }
  }

  @override
  void onInit() {
    super.onInit();

    // 检查是否传入了初始标签索引
    final arguments = Get.arguments;
    final initialTabIndex =
        arguments != null && arguments.containsKey('initialTabIndex')
            ? arguments['initialTabIndex'] as int
            : 0;

    // 初始化TabController
    tabController = TabController(
      length: 4,
      vsync: this,
      initialIndex: initialTabIndex,
    );

    _initData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}
